package com.ruoyi.common.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.regex.*;

public class FFmpegDurationChecker {

    public static void main(String[] args) throws IOException {
        File videoFile = new File("D:\\BaiduNetdiskDownload\\CS-视频问答\\测试视频1.mp4"); // 替换为你的视频路径
        getDurationWithFFmpeg(videoFile);
    }

    public static String getDurationWithFFmpeg(File videoFile) throws IOException {
        String duration = "";
        ProcessBuilder pb = new ProcessBuilder(
                "ffmpeg", "-i", videoFile.getAbsolutePath()
        );

        pb.redirectErrorStream(true); // 合并错误流到标准输出
        Process process = pb.start();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {

            String line;
            Pattern durationPattern = Pattern.compile("Duration: (\\d{2}):(\\d{2}):(\\d{2}\\.\\d+)");

            while ((line = reader.readLine()) != null) {
                Matcher matcher = durationPattern.matcher(line);
                if (matcher.find()) {
                    int hours = Integer.parseInt(matcher.group(1));
                    int minutes = Integer.parseInt(matcher.group(2));
                    float seconds = Float.parseFloat(matcher.group(3));

                    long totalMillis = (long) ((hours * 3600 + minutes * 60 + seconds) * 1000);
                    duration = formatDuration(totalMillis);
                    System.out.println("视频时长: " + duration);
                    return duration;
                }
            }
            throw new IOException("无法在FFmpeg输出中找到时长信息");
        } finally {
            process.destroy();
        }
    }

    // 格式化方法同上
    // 格式化时长 (小时:分钟:秒)
    private static String formatDuration(long millis) {
        long seconds = millis / 1000;
        long hours = seconds / 3600;
        long minutes = (seconds % 3600) / 60;
        seconds = seconds % 60;
        return String.format("%02d",  seconds);
    }
}